package ace.cmp.data.methodname.method.name.sql.entity.resolver.impl.property;

import ace.cmp.data.methodname.method.name.sql.core.enums.SqlCommandTypeEnum;
import ace.cmp.data.methodname.method.name.sql.entity.model.EntityMapping;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;

/**
 * @author caspar
 * @date 2023/2/18 11:17 1. 出参为普通类型直接解析为选择列
 * 2. 出参泛型类型第一个泛型类型属性为选择列
 */
public class SelectQueryPropertyOutParameterFirstGenericResolverImpl
    extends AbstractSelectQueryPropertyResolver {

  public SelectQueryPropertyOutParameterFirstGenericResolverImpl(
      SqlCommandTypeEnum sqlCommandType, Method method, EntityMapping entityMapping) {
    super(sqlCommandType, method, entityMapping);
  }

  @Override
  protected Class resolveClass() {
    Class cls = null;
    Type genericReturnType = this.getMethod().getGenericReturnType();
    // 泛型返回类型
    if (genericReturnType instanceof ParameterizedType) {
      Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
      if (actualTypeArguments.length == 0) {
        return null;
      }
      Type firstActualTypeArgument = actualTypeArguments[0];
      try {
        cls = Class.forName(firstActualTypeArgument.getTypeName());
      } catch (ClassNotFoundException e) {

      }
    } else {
      if (genericReturnType instanceof TypeVariable) {
        return null;
      }
      cls = (Class) genericReturnType;
    }
    if (this.isNotCustomClass(cls)) {
      return null;
    }
    return cls;
  }
}
